package tech.mhuang.pacebox.springboot.autoconfiguration.trace.rest;

import io.opentracing.Span;
import io.opentracing.contrib.spring.web.client.RestTemplateSpanDecorator;
import io.opentracing.tag.Tags;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import tech.mhuang.pacebox.core.exception.ExceptionUtil;
import tech.mhuang.pacebox.core.io.IOUtil;

import java.io.IOException;
import java.util.Map;

/**
 * restTemplate span埋点
 *
 * @author mhuang
 * @since 1.0.0
 */
public class TraceRestTemplateSpanDecorator implements RestTemplateSpanDecorator {
    private static final Log log = LogFactory.getLog(StandardTags.class);

    public static final String COMPONENT_NAME = "java-spring-rest-template";

    @Override
    public void onRequest(HttpRequest request, Span span) {
        Tags.COMPONENT.set(span, COMPONENT_NAME);
        Tags.HTTP_URL.set(span, request.getURI().toString());
        Tags.HTTP_METHOD.set(span, request.getMethod().toString());
        if (request.getURI().getPort() != -1) {
            Tags.PEER_PORT.set(span, request.getURI().getPort());
        }
    }

    @Override
    public void onResponse(HttpRequest httpRequest, ClientHttpResponse response, Span span) {
        try {
            Tags.HTTP_STATUS.set(span, response.getStatusCode().value());
            String content = IOUtil.toString(response.getBody());
            span.setTag("response", content);
        } catch (IOException e) {
            log.error("Could not get HTTP status code");
        }
    }

    @Override
    public void onError(HttpRequest httpRequest, Throwable ex, Span span) {
        Tags.ERROR.set(span, Boolean.TRUE);
        Map<String, String> log = ExceptionUtil.logsForException(ex);
        log.put("event", Tags.ERROR.getKey());
        span.log(log);
    }
}